import 'dart:async';
import 'dart:io';

import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';

Future<String> copyAssetFileToTmp(String assetPath) async {
  final tmpDir = await getTemporaryDirectory();
  final tmpPath = '${tmpDir.path}/${assetPath.split('/').last}';
  final byteData = await rootBundle.load(assetPath);
  final file = File(tmpPath);
  await file.writeAsBytes(byteData.buffer.asUint8List());
  return tmpPath;
}

/// 任务管理器，一个任务管理器名对应一个单例，保证任务顺序执行
class TaskHelper {
  Future<void> _executionChain = Future.value(null);
  Completer<void>? _allTasksCompleter;
  int _pendingCount = 0;
  final String helperName;

  TaskHelper._internal(this.helperName);

  static final Map<String, TaskHelper> _instances = {};

  factory TaskHelper(String helperName) => _instances.putIfAbsent(
      helperName, () => TaskHelper._internal(helperName));

  @override
  int get hashCode => helperName.hashCode;

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is TaskHelper && helperName == other.helperName;

  /// 添加一个任务，并返回一个Future，当任务执行完成时，Future会返回结果，如果任务执行失败，Future会抛出异常
  Future<T> addTask<T>(Function task) {
    if (_pendingCount == 0) {
      _allTasksCompleter = Completer();
    }
    _pendingCount++;

    final taskCompleter = Completer<T>();

    _executionChain = _executionChain.then((_) async {
      try {
        final result = await task();
        taskCompleter.complete(result);
      } catch (e, s) {
        taskCompleter.completeError(e, s);
      } finally {
        if (--_pendingCount == 0) {
          _allTasksCompleter?.complete();
        }
      }
    });

    return taskCompleter.future;
  }

  /// 添加一个任务，当任务队列为空时，才执行该任务，否则返回null
  Future<T?> addTaskWhileIdle<T>(Function task) {
    if (_pendingCount != 0) {
      return Future.value(null);
    }
    return addTask(task);
  }

  /// 等待所有任务执行完成
  Future<void> waitAllTaskDone() async {
    if (_pendingCount == 0) return;
    await _allTasksCompleter?.future;
  }
}
